<template>
  <editor-layout @ok="handleOk" v-on="$listeners" v-loading="loading">
    <el-form :model="model" :rules="rule" ref="form" @keyup.enter.native="handleOk()" label-width="110px">
      <el-form-item label="字典代码" prop="value">
        <el-input v-model="model.value" placeholder="字典代码" clearable/>
      </el-form-item>
      <el-form-item label="字典名称" prop="label">
        <el-input v-model="model.label" placeholder="字典名称" clearable/>
      </el-form-item>
      <el-form-item label="字典类别代码" prop="type">
        <el-input v-model="model.type" placeholder="字典类别代码" clearable/>
      </el-form-item>
      <el-form-item label="字典类别名称" prop="typeCn">
        <el-input v-model="model.typeCn" placeholder="字典类别名称" clearable/>
      </el-form-item>
    </el-form>
  </editor-layout>
</template>

<script>
import {postSysSysdictionarySave, postSysSysdictionaryUpdate, getSysSysdictionaryInfoId} from '$my/code/api/sys-dictionary'

export default {
  name: 'edit',
  props: {
    id: [String, Number]
  },
  data() {
    return {
      loading: false,
      model: {
        value: '',
        label: '',
        type: '',
        typeCn: ''
      },
      rule: {
        value: [{required: true, message: '必填项'}],
        label: [{required: true, message: '必填项'}],
        type: [{required: true, message: '必填项'}],
        typeCn: [{required: true, message: '必填项'}]
      }
    }
  },
  methods: {
    init() {
      console.info('init-' + this.id)
      if(this.id) {
        this.loadForm()
      }
    },
    async loadForm() {
      this.loading = true
      const data = await getSysSysdictionaryInfoId(this.id).catch(e => {
        this.loading = false
        throw new Error(e)
      })
      this.model = {...data}
      this.loading = false
    },
    handleOk() {
      this.$refs.form.validate(ok => {
        if (!ok) return
        let fn = postSysSysdictionarySave
        if (typeof this.id !== 'undefined') {
          fn = postSysSysdictionaryUpdate
        }

        this.loading = true
        fn({...this.model}).then(res => {
          this.$notify.success('操作成功!')
          this.$emit('on-ok')
        })
      })
    }
  },
  mounted() {
    this.init()
  }
}
</script>

<style lang="scss" scoped>
.edit {

}
</style>
